package com.xx.springboot.config.shiro;

import com.xx.springboot.entity.CommonResult;
import com.xx.springboot.entity.Permission;
import com.xx.springboot.entity.Role;
import com.xx.springboot.entity.User;
import com.xx.springboot.service.IRoleService;
import com.xx.springboot.service.IUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * Created by xiaoxiunique on 2018-9-14.
 */
public class UserRealm extends AuthorizingRealm {

    /**
     * 没有找到用户的情况
     */
    public static final String NOT_FOUND_ACCOUNT = "-1";


    @Autowired
    private IUserService userService;

    @Autowired
    private IRoleService roleService;

    /**
     * 记录日志
     */
    private Logger logger  = LoggerFactory.getLogger(UserRealm.class);



    /**
     * <p>
     *      TODO:授权
     * </p>
     * @Author hcg
     * @Date 2018-11-15 14:22
     * @Param
     * @return AuthorizationInfo
     **/
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        User roleUser = userService.getUserListRole(user.getId());

        //设置角色
        Set<String> roleSet = new HashSet<String>();
        roleUser.getRoleList().forEach(e -> {
            roleSet.add(e.getName());
        });
        Set<String> permissionSet = new HashSet<>();

        for (Role role:roleUser.getRoleList()){
            Role permissionRole = roleService.getRoleListPermission(role.getId());
            List<Permission> permissions = permissionRole.getPermissionList();
            for (Permission p : permissions) {
                permissionSet.add(p.getName());
            }
        }
        // 为当前用户设置权限
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();

        authorizationInfo.setRoles(roleSet);
        authorizationInfo.setStringPermissions(permissionSet);
        return authorizationInfo;
    }

    /**
     * 验证当前登录的 Subject
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String loginName = (String) authenticationToken.getPrincipal();

        //获取用户密码
        String password = new String((char[])authenticationToken.getCredentials());
        CommonResult out = userService.loginUser(loginName, password);

        if(NOT_FOUND_ACCOUNT.equals(out.getStats())){
            // 没找到账号13
            throw new UnknownAccountException("没有找到账号");
        }

        User user = (User) out.getMain();
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(user, password, getName());
        return authenticationInfo;
    }
}
